<template>
  <div>
    <el-form
      label-width="200px"
      style="max-width: 600px"
      :rules="rules"
      :model="uploadConfig"
      ref="formRef"
    >
      <el-form-item label="网页标题：" prop="title">
        <el-input
          type="primary"
          v-model.trim="uploadConfig.title"
          autocomplete="off"
          size="small"
        ></el-input>
      </el-form-item>

      <el-form-item label="网页文件名：" prop="webPageFileName">
        <el-input
          type="primary"
          v-model.trim="uploadConfig.webPageFileName"
          autocomplete="off"
          size="small"
        ></el-input>
        <span style="color: red">只支持英文，如:work11</span>
      </el-form-item>

      <el-form-item label="版本发布日期：" prop="version">
        <el-date-picker
          v-model="uploadConfig.version"
          type="date"
          size="small"
          format="MMDD"
          value-format="MMDD"
          :disabled-date="disabledDate"
        />
      </el-form-item>

      <el-form-item label="上传图片：" prop="imgList">
        <el-upload
          ref="uploadRef"
          class="upload-demo"
          :on-change="handleChange"
          v-model="uploadConfig.imgList"
          :file-list="uploadConfig.imgList"
          :auto-upload="false"
          :action="uploadApi"
          :data="uploadConfig"
          :on-exceed="handleExceed"
          :limit="1"
          :on-success="handleSuccess"
        >
          <template #trigger>
            <el-button type="primary">选择图片</el-button>
          </template>
          <template #tip>
            <div class="el-upload__tip">jpg/png文件最多500kb</div>
          </template>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit(formRef)">上传</el-button>
      </el-form-item>
    </el-form>
    <fieldset>
      <legend>网页数据</legend>
      <div class="container">
        <div class="right">
          <el-form :inline="true">
            <el-form-item label="网页标题：">
              <el-autocomplete
                v-model="searchTitle"
                :fetch-suggestions="querySearch"
                placeholder="请输入网页标题（支持拼音搜索）"
                style="width: 240px"
                clearable
                @select="handleSelect"
                @clear="handleClear"
                @keyup.enter="handleSearch"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch" size="small"
                >查询</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </div>
      <el-table
        ref="multipleTableRef"
        :data="currentPageData"
        style="width: 100%"
        :cell-style="highlightCell"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column prop="filename" label="网页在线地址" width="800px">
          <template #default="scope">
            <a :href="scope.row.filename" target="_blank">{{
              scope.row.filename
            }}</a>
          </template>
        </el-table-column>
        <el-table-column
          prop="title"
          label="标题"
          width="165px"
        ></el-table-column>
        <el-table-column prop="img_name" label="图片名"></el-table-column>
        <el-table-column
          prop="last_commit_time"
          label="网页最后修改时间"
          width="120px"
        ></el-table-column>
        <el-table-column
          prop="img_mod_times"
          label="图片修改时间"
        ></el-table-column>
      </el-table>
      <el-pagination
        v-if="total > pageSize"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next"
        @current-change="handleCurrentChange"
      />
    </fieldset>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed } from "vue";
import { genFileId } from 'element-plus'
import type { FormInstance, FormRules,UploadProps,UploadRawFile } from "element-plus";
import { getHtmlInformationApi,uploadApi } from "@/api/modules/upload";
import { errorTip, okTip } from "@/utils/messageTip";

// 简单的汉字转拼音函数
const chineseToPinyin = (text: string): string => {
  // 这里使用一个简化的实现，实际项目中建议使用专业的拼音库如 pinyin.js
  const pinyinMap: { [key: string]: string } = {
    '我': 'wo', '你': 'ni', '他': 'ta', '她': 'ta', '它': 'ta',
    '们': 'men', '的': 'de', '是': 'shi', '在': 'zai', '有': 'you',
    '和': 'he', '与': 'yu', '或': 'huo', '了': 'le', '这': 'zhe',
    '那': 'na', '个': 'ge', '一': 'yi', '二': 'er', '三': 'san',
    '四': 'si', '五': 'wu', '六': 'liu', '七': 'qi', '八': 'ba',
    '九': 'jiu', '十': 'shi', '百': 'bai', '千': 'qian', '万': 'wan',
    '上': 'shang', '下': 'xia', '左': 'zuo', '右': 'you', '前': 'qian',
    '后': 'hou', '大': 'da', '小': 'xiao', '多': 'duo', '少': 'shao',
    '高': 'gao', '低': 'di', '长': 'chang', '短': 'duan', '好': 'hao',
    '坏': 'huai', '新': 'xin', '旧': 'jiu', '东': 'dong', '南': 'nan',
    '西': 'xi', '北': 'bei'
  };
  
  return text.split('').map(char => {
    // 如果是汉字，返回对应的拼音，否则返回原字符
    return pinyinMap[char] || char;
  }).join('');
};

import VConsole from "vconsole";
import { a } from "vite/dist/node/types.d-aGj9QkWt";

onMounted(() => {
  const vConsole = new VConsole() 
  console.log(vConsole);
  getHtmlInformation();
});

const uploadConfig = reactive({
  title: "",
  webPageFileName: "",
  code: "",
  version:"",
  imgList: [],
});

const uploadRef = ref();

const formRef = ref<FormInstance>();

const rules = reactive<FormRules>({
  title: [{ required: true, message: "请输入网页标题!", trigger: "blur" }],
  webPageFileName: [
    { required: true, message: "请输入网页文件名!", trigger: "blur" },
  ],
  // code: [{ required: true, message: "请输入上传网页秘钥!", trigger: "blur" }],
  imgList: [{ required: true, message: "请上传图片", trigger: "blur" }],
  version: [{ required: true, message: "请选择版本信息", trigger: "blur" }],
});

const handleChange = (file: any, fileList: any) => {
  uploadConfig.imgList = fileList;
};

const onSubmit = async (formEl: FormInstance | undefined) => {
  console.log(uploadConfig);
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      uploadRef.value.submit();
    } else {
      console.log("error submit!", fields, formEl);
    }
  });
};

const handleSuccess =(resp:any)=>{
  console.log(resp);
  if(resp.ec == 200){
    okTip(resp.data.message)
    renderTable(resp.data.data)
  }else{
    errorTip(resp.data.message)
  }
}

const currentPageData:any = ref([]);
const htmlInfoMationTabel: any = ref([]);

const searchTitle = ref("");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

const getHtmlInformation = async () => {
  let resp: any = await getHtmlInformationApi({});
  let tableInfos: any = resp.data;
  renderTable(tableInfos)
};

const renderTable = (data:any)=>{
  htmlInfoMationTabel.value = data;
  total.value = data.length;
  handleCurrentChange(1);
}

// 搜索过滤函数 - 支持模糊匹配和拼音搜索
const filterByKeyword = (items: any[], keyword: string): any[] => {
  if (!keyword || !keyword.trim()) {
    return items;
  }
  
  const lowerKeyword = keyword.toLowerCase().trim();
  
  return items.filter(item => {
    const title = item.title || '';
    const lowerTitle = title.toLowerCase();
    const pinyinTitle = chineseToPinyin(title).toLowerCase();
    const pinyinKeyword = chineseToPinyin(keyword).toLowerCase();
    
    // 匹配规则：
    // 1. 标题中包含关键词
    // 2. 标题的拼音中包含关键词
    // 3. 标题中包含关键词的拼音
    return lowerTitle.includes(lowerKeyword) || 
           pinyinTitle.includes(lowerKeyword) ||
           pinyinTitle.includes(pinyinKeyword);
  });
};

// 联想搜索建议 - 支持拼音搜索
const querySearch = (queryString: string, cb: (data: any[]) => void) => {
  if (!queryString) {
    cb([]);
    return;
  }
  
  // 使用过滤函数获取匹配结果
  const results = filterByKeyword(htmlInfoMationTabel.value, queryString)
    .slice(0, 10) // 限制显示10条建议
    .map((item: any) => ({
      value: item.title,
      label: item.title
    }));
  
  cb(results);
};

// 选择建议项
const handleSelect = () => {
  handleSearch();
};

// 清空搜索
const handleClear = () => {
  searchTitle.value = '';
  renderTable(htmlInfoMationTabel.value);
};

// 搜索功能 - 支持拼音搜索的模糊筛选
const handleSearch = () => {
  const keyword = searchTitle.value;
  
  if (!keyword.trim()) {
    renderTable(htmlInfoMationTabel.value);
    return;
  }
  
  // 使用过滤函数获取搜索结果
  const filteredData = filterByKeyword(htmlInfoMationTabel.value, keyword);
  
  if (filteredData.length > 0) {
    // 显示搜索结果
    currentPageData.value = filteredData;
    total.value = filteredData.length;
    currentPage.value = 1;
  } else {
    currentPageData.value = [];
    total.value = 0;
    errorTip('未找到匹配的网页标题');
  }
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  const start = (val - 1) * pageSize.value;
  const end = start + pageSize.value;
  currentPageData.value = htmlInfoMationTabel.value.slice(start, end);
};

const highlightCell = ({ row }: any) => {
  if (searchTitle.value && row.title.toLowerCase().includes(searchTitle.value.toLowerCase())) {
    return { backgroundColor: "#ebf5ff !important" };
  }
};

const multipleSelection = ref();

const handleSelectionChange = (val: any) => {
  multipleSelection.value = val;
};

const handleExceed: UploadProps['onExceed'] = (files:any) => {
  uploadRef.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  uploadRef.value!.handleStart(file)
}

const disabledDate = (time: Date) => {
  return time.getTime() <  new Date().getTime() - 86400000;
}
</script>

<style scoped>
.container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.left {
  flex: 1;
}
.right {
  margin-left: 20px;
}
.highlight {
  background-color: red;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
